using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using MvcContrib;
using ThunderJob.Controllers.Anuncio.ViewModels;
using ThunderJob.Controllers.Extensions;
using ThunderJob.Controllers.Security;
using ThunderJob.Domain.Services;
using ThunderJob.Domain.Validation;

namespace ThunderJob.Controllers.Anuncio
{
    public class AnuncioController : Controller
    {
        public IReclutarPersonalService ReclutarPersonalService { get; private set; }
        public IMappingEngine MappingEngine { get; private set; }

        public AnuncioController(IReclutarPersonalService reclutarPersonalService, IMappingEngine mappingEngine)
        {
            ReclutarPersonalService = reclutarPersonalService;
            MappingEngine = mappingEngine;
        }

        public ActionResult Crear()
        {
            return View(AnuncioViewModel.NUEVO);
        }

        public ActionResult Crear(IUserIdentity empresaAutenticada, AnuncioViewModel viewModel)
        {
            Domain.Anuncio anuncio = MappingEngine.Map<AnuncioViewModel, Domain.Anuncio>(viewModel);
            try
            {
                ReclutarPersonalService.Publicar(empresaAutenticada.Id, anuncio);
            }
            catch (ValidationException e)
            {
                return View(viewModel).Errors(e);
            }
            return this.RedirectToAction(x => x.Index(empresaAutenticada));
        }

        public ActionResult Index(IUserIdentity empresaAutenticada)
        {
            IEnumerable<Domain.Anuncio> anuncios = ReclutarPersonalService.AnunciosPublicados(empresaAutenticada.Id);
            IEnumerable<AnuncioViewModel> viewModels = MappingEngine.Map<IEnumerable<Domain.Anuncio>, IEnumerable<AnuncioViewModel>>(anuncios);
            return View(viewModels);
        }
    }
}